﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EditMode
{
    /// <summary> 
    /// Methods for converting between Edit and DSC units.
    /// </summary>
    public class Utilities
    {
        private const float PositionMultiplier = 362.5f;
        private const float PVTimeMultiplier = 1666.666f;

        /// <summary> 
        /// Calculate edit PV time based on DSC timestamp. 
        /// </summary>
        public static uint CalculatePVTime(uint timestamp)
        {
            return Convert.ToUInt32(timestamp / PVTimeMultiplier);
        }

        /// <summary> 
        /// Calculate edit target position based on DSC position. 
        /// </summary>
        public static float CalculateTargetPosition(uint position)
        {
            return position / PositionMultiplier;
        }

        /// <summary> 
        /// Calculate edit target entry angle based on DSC angle. 
        /// </summary>
        public static float CalculateAngle(int angle)
        {
            return (angle + 5000) / 1000;
        }

        /// <summary> 
        /// Edit String to byte[]. 
        /// </summary>
        public static byte[] GetBytes(string inputString, int length, Encoding encoding)
        {
            byte[] encodedString = Encoding.BigEndianUnicode.GetBytes(inputString); ;
            if (encoding == Encoding.ASCII)
            {
                encodedString = Encoding.ASCII.GetBytes(inputString);
            }
            else if (encoding == Encoding.Unicode)
            {
                encodedString = Encoding.BigEndianUnicode.GetBytes(inputString);
            }
            else if (encoding == Encoding.UTF8)
            {
                encodedString = Encoding.UTF8.GetBytes(inputString);
            }
            var stringBytes = new List<byte>();
            for (byte i = 0; i < length; i++)
            {
                try { stringBytes.Add(encodedString.ElementAt(i)); }
                catch (Exception) { stringBytes.Add(0x00); }
            }
            byte[] bytes = new byte[length];
            for (int i = 0; i < length; i++)
            {
                bytes[i] = stringBytes[i];
            }
            return bytes;
        }
        
        /// <summary> 
        /// Edit byte[] to string. 
        /// </summary>
        public static string GetString(byte[] bytes, Encoding encoding)
        {
            if (encoding == Encoding.UTF8)
            {
                return Encoding.UTF8.GetString(bytes).Trim((char)0x00);
            }
            else if (encoding == Encoding.Unicode)
            {
                return Encoding.BigEndianUnicode.GetString(bytes).Trim((char)0x00);
            }
            else if (encoding == Encoding.ASCII)
            {
                return Encoding.ASCII.GetString(bytes).Trim((char)0x00);
            }
            return "ERROR";
        }
    }
}
